import { useEffect, useRef, useState } from 'react';
import { Card, Progress, message } from 'antd';
import { LoadingOutlined, CameraOutlined, CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons';
import axios from 'axios';
import { Notify, Toast } from 'react-vant';
import { NavBar, Button } from 'react-vant';
import { Flex, Spin } from 'antd';
import { useNavigate } from 'react-router-dom';
import style from './login'; // 假设这里的样式文件存在且正确
import FaceImg from '../assets/face.jpg';
import { LeftOutlined } from '@ant-design/icons'; // 导入 antd 的左箭头图标

function Face(props) {
  let video = useRef(null);
  const navigate = useNavigate();
  let canvas = useRef(null);
  let [imgSrc, setImgSrc] = useState('');
  const [isShow, setIsShow] = useState(false);
  const [faceStatus, setFaceStatus] = useState('开始拍摄');
  const [isLoadshow, setIsLoadshow] = useState(false);
  const [verificationState, setVerificationState] = useState('idle'); // idle | scanning | processing | success | fail
  const [progress, setProgress] = useState(0);
  const [stream, setStream] = useState(null); // 存储摄像头流，方便关闭
  const [showCaptureButton, setShowCaptureButton] = useState(false);

  // 打开摄像头的方法
  const open = async () => {
    setIsShow(true);
    try {
      if (!navigator.mediaDevices) {
        navigator.mediaDevices = {};
      }
      if (!navigator.mediaDevices.getUserMedia) {
        navigator.mediaDevices.getUserMedia = function (constraints) {
          const getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
          if (!getUserMedia) {
            return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
          }
          return new Promise((resolve, reject) => {
            getUserMedia.call(navigator, constraints, resolve, reject);
          });
        };
      }
      const newStream = await navigator.mediaDevices.getUserMedia({
        video: true,
        audio: false,
      });
      setStream(newStream);
      if (video.current) {
        video.current.srcObject = newStream;
        video.current.play();
      }
    } catch (err) {
      console.error('摄像头打开失败', err);
      Notify.show({ type: 'danger', message: '摄像头打开失败，请检查权限或设备' });
    }
  };

  // 关闭摄像头
  const close = () => {
    setIsShow(false);
    if (stream) {
      stream.getTracks().forEach(track => track.stop());
      setStream(null);
    }
  };

  // 截取视频画面  和人脸库对比人员信息
  const drawMedia = async () => {
    setVerificationState('processing'); // 点击拍摄后设置为 processing 状态
    setProgress(0);
    // 模拟处理进度
    const timer = setInterval(() => {
      setProgress(prev => {
        if (prev >= 100) {
          clearInterval(timer);
          return 100;
        }
        return prev + 10;
      });
    }, 300);

    if (!canvas.current || !video.current) return;
    const ctx = canvas.current.getContext('2d');
    if (!ctx) return;

    ctx.clearRect(0, 0, canvas.current.width, canvas.current.height);
    ctx.drawImage(
      video.current,
      (canvas.current.width - canvas.current.width * (320 / 240)) / 2,
      0,
      canvas.current.width * (320 / 240),
      canvas.current.height,
    );

    const base64 = canvas.current.toDataURL('image/jpeg');
    setImgSrc(base64);

    try {
      const { data } = await axios.post('http://localhost:3010/faceLogin', {
        base64: base64.split(',')[1],
      }, { timeout: 5000 }); // 添加请求超时处理

      if (data.code === -1) {
        Notify.show({ type: 'danger', message: '人脸未通过，请注册' });
        setVerificationState('fail');
      } else {
        Notify.show({ type: 'success', message: '人脸识别成功' });
        setVerificationState('success');
        setTimeout(() => {
          navigate('/tabber/first');
          close();
        }, 500);
      }
    } catch (error) {
      console.error('人脸识别请求失败', error);
      Notify.show({ type: 'danger', message: '人脸识别请求失败，请重试' });
      setVerificationState('fail');
    }
  };

  const startVerification = () => {
    setVerificationState('scanning');
    open();
    setShowCaptureButton(true); // 显示立即拍摄按钮
  };

  const getVerificationContent = () => {
    switch (verificationState) {
      case 'idle':
        return (
          <div style={{ textAlign: 'center', padding: '4vw 0', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
            <CameraOutlined style={{ fontSize: '12vw', color: '#1890ff', marginBottom: '2vw' }} />
            <p style={{ fontSize: '5vw', fontWeight: 'bold', marginBottom: '2vw' }}>请正对摄像头准备人脸验证</p>
            
              <Button
                type="primary"
                size="normal"
                onClick={startVerification}
                className="face-verification-button"
              >
                开始验证
              </Button>
              <span style={{position:"absolute",left:"3rem",bottom:"0.2rem",fontSize:"0.3rem"}}>还没有录入人脸?<span style={{color:"blue"}} onClick={()=>{navigate('/addPerson')}}>立即录入</span></span>
          </div>
        );
      case 'scanning':
        return (
          <div style={{ textAlign: 'center', padding: '4vw 0' }}>
            <p style={{ fontSize: '5vw', fontWeight: 'bold' }}>摄像头已打开，请点击立即拍摄</p>
          </div>
        );
      case 'processing':
        return (
          <div style={{ textAlign: 'center', padding: '4vw 0', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
            <Spin
              indicator={<LoadingOutlined style={{ fontSize: '12vw', color: '#1890ff' }} spin />}
            />
            <p style={{ fontSize: '5vw', fontWeight: 'bold', marginTop: '2vw' }}>正在验证人脸信息</p>
            <Progress
              percent={progress}
              status="active"
              style={{ maxWidth: '70vw', width: '90%', marginTop: '2vw' }}
            />
          </div>
        );
      case 'success':
        return (
          <div style={{ textAlign: 'center', padding: '4vw 0', color: '#52c41a', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
            <CheckCircleOutlined style={{ fontSize: '16vw', marginBottom: '2vw' }} />
            <p style={{ fontSize: '6vw', fontWeight: 'bold', marginBottom: '1vw' }}>验证成功</p>
            <p style={{ fontSize: '5vw', marginBottom: '2vw' }}>人脸信息匹配成功</p>
            <Button
              type="primary"
              size="large"
              onClick={() => {
                setVerificationState('idle');
                close();
              }}
              style={{ width: '30vw', fontSize: '3vw' }}
            >
              返回
            </Button>
          </div>
        );
      case 'fail':
        return (
          <div style={{ textAlign: 'center', padding: '4vw 0', color: '#f5222d', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
            <CloseCircleOutlined style={{ fontSize: '16vw', marginBottom: '2vw' }} />
            <p style={{ fontSize: '6vw', fontWeight: 'bold', marginBottom: '1vw' }}>验证失败</p>
            <p style={{ fontSize: '5vw', marginBottom: '2vw' }}>人脸信息不匹配或质量不佳</p>
            <Button
              type="primary"
              danger
              size="large"
              onClick={() => {
                setVerificationState('idle');
                close();
              }}
              style={{ width: '30vw', fontSize: '3vw' }}
            >
              重试
            </Button>
          </div>
        );
      default:
        return null;
    }
  };

  useEffect(() => {
    return () => {
      close(); // 组件卸载时关闭摄像头
    };
  }, []);

  return (
    <div>
      <NavBar
        title="人脸识别"
        leftText="1111"
        // 自定义左侧箭头图标，设置颜色为黑色
        leftArrow={<LeftOutlined style={{ color: 'black' }} />}
        onClickLeft={props.handleClose}
        onClickRight={() => Toast('按钮')}
        style={{ width: "100%", height: "50px", color: "black" }}
      />
      {isLoadshow ? <Spin indicator={<LoadingOutlined style={{ fontSize: '10vw' }} spin />} /> : null}
      <div style={{ maxWidth: '95vw', margin: '0 auto', padding: '5vw' }}>
        <canvas style={{ display: "none" }} ref={canvas} width="300" height="300"></canvas>
        <div style={{
          display: isShow ? 'flex' : 'none',
          justifyContent: 'center',
          alignItems: 'center',
          height: '40vh',
          marginTop: '4vh'
        }}>
          <video
            ref={video}
            preload="auto"
            autoPlay
            loop
            muted
            style={{
              width: '6rem',
              height: '6rem',
              borderRadius: "50%",
              objectFit: "cover",
            }}
          />
        </div>
        {getVerificationContent()}
        {showCaptureButton && verificationState === 'scanning' && (
          <Button
            type="primary"
            size="large"
            onClick={drawMedia}
            style={{ width: '30vw', fontSize: '3vw', marginTop: '2vw', display: 'block', margin: '0 auto' }}
          >
            立即拍摄
          </Button>
        )}
      </div>
    </div>
  );
}

export default Face;
